package com.lee.mao.adapter;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.viewpager.widget.PagerAdapter;

import com.lee.mao.R;
import com.lee.mao.base.Mapplication;
import com.lee.mao.bean.ClassifyTable;
import com.lee.mao.bean.MoneyTable;
import com.lee.mao.bean.TypeValue;
import com.lee.mao.database.utils.DateHelper;
import com.lee.mao.database.utils.MoneyTableUtil;
import com.lee.mao.utils.AutoNextLineLinearLayout;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class TypeAdapter extends PagerAdapter {
    Context context;
    List<View> viewList;
    protected SharedPreferences sp;
    private List<ClassifyTable> allClassify;

    Mapplication mapplication;
    private static final String TAG = "TypeAdapter";

    public TypeAdapter(Context context, List<View> views, List<ClassifyTable> classifies) {
        this.context = context;
        viewList = views;
        allClassify = classifies;
        mapplication = (Mapplication) context.getApplicationContext();
        sp = context.getSharedPreferences("mao", Context.MODE_PRIVATE);
    }

    @Override
    public int getCount() {
        return viewList.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public View instantiateItem(ViewGroup container, int position) {
        View view = viewList.get(position);
        container.addView(view);

        if (allClassify.get(position).getType() == TypeValue.CLASSIFY_TYPE_EDIT) {
            editType(view, position);
        } else if (allClassify.get(position).getType() == TypeValue.CLASSIFY_TYPE_BOOKKEEPING) {
            bookType(view, position);
        }

        return view;
    }

//    List<MoneyTable> chargeByTime = null;

    private void bookType(View view, int position) {

        ImageView plus = view.findViewById(R.id.ivPlus);
        EditText etName = view.findViewById(R.id.etName);
        EditText etMoney = view.findViewById(R.id.etMoney);
        TextView tvDate = view.findViewById(R.id.tvDate);

        RecyclerView recycle = view.findViewById(R.id.recycle);

        LinearLayoutManager ms = new LinearLayoutManager(context);
        ms.setOrientation(LinearLayoutManager.HORIZONTAL);
        recycle.setLayoutManager(ms);
        List<String> txts = new ArrayList<>();
        txts.add("吃饭");
        txts.add("买菜");
        txts.add("e卡");
        txts.add("超市");
        txts.add("话费");
        TextAdapter textAdapter = new TextAdapter(txts, context);
        recycle.setAdapter(textAdapter);
        textAdapter.setTextItemClick(new TextAdapter.TextItemClick() {
            @Override
            public void onclick(int position) {
                etName.setText(txts.get(position));
            }
        });
//        TextView t1 = view.findViewById(R.id.t1);
//        TextView t2 = view.findViewById(R.id.t2);
//        TextView t3 = view.findViewById(R.id.t3);
//        TextView t4 = view.findViewById(R.id.t4);
//
//        t4.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//
//            }
//        });

//        AutoNextLineLinearLayout autoView = view.findViewById(R.id.autoLayout);
        tvDate.setText(DateHelper.getCurDateStr(DateHelper.FORMAT_MD));

        try {
            Calendar calendar = Calendar.getInstance();

            List<List<MoneyTable>> chargeList = new ArrayList<>();

            getAllCharge(position, chargeList);

            RecyclerView recyclerView = view.findViewById(R.id.recyclerView);
            // 设置布局管理器
            RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(context);
            recyclerView.setLayoutManager(mLayoutManager);
            ChargeAdapter chargeAdapter = new ChargeAdapter(context, chargeList);
            recyclerView.setAdapter(chargeAdapter);
            SwipeRefreshLayout swipe_refresh = view.findViewById(R.id.swipe_refresh);
            swipe_refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {

                    swipe_refresh.setRefreshing(false);
                    getAllCharge(position, chargeList);
                    chargeAdapter.notifyDataSetChanged();
                }
            });

            plus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    String name = etName.getText().toString();
                    String money = etMoney.getText().toString();

                    if (TextUtils.isEmpty(name) || TextUtils.isEmpty(money))
                        return;

                    try {

                        MoneyTable moneyTable = new MoneyTable(name, calendar.getTimeInMillis(), money);

                        if (position == 1) {//支出
                            moneyTable.setType(TypeValue.MONEY_PAY);
                            Log.d(TAG, "支出插入成功");
                        } else if (position == 2) {//收入
//                        IncomeTableUtil.getInstance(mapplication).addIncome(new IncomeTable(name, System.currentTimeMillis(), money));
                            moneyTable.setType(TypeValue.MONEY_INCOME);
                            Log.d(TAG, "收入插入成功");
                        }

                        etName.setText("");
                        etMoney.setText("");
                        etName.clearFocus();
                        MoneyTableUtil.getInstance(mapplication).addCharge(moneyTable);

                        List<MoneyTable> moneyTables = chargeList.get(0);
                        moneyTables.add(0, moneyTable);

                        chargeAdapter.notifyDataSetChanged();
                        //notifyDataSetChanged();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }


                }
            });

            tvDate.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    DatePickerDialog dialog = new DatePickerDialog(context,
                            new DatePickerDialog.OnDateSetListener() {
                                @Override
                                public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                                    Log.d(TAG, "onDateSet: year: " + year + ", month: " + month + ", dayOfMonth: " + dayOfMonth);

                                    calendar.set(Calendar.YEAR, year);
                                    calendar.set(Calendar.MONTH, month);
                                    calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                                    tvDate.setText(DateHelper.date2Str(calendar, DateHelper.FORMAT_MD));
                                }
                            },
                            calendar.get(Calendar.YEAR),
                            calendar.get(Calendar.MONTH),
                            calendar.get(Calendar.DAY_OF_MONTH));
                    dialog.show();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void getAllCharge(int position, List<List<MoneyTable>> chargeList) {

        chargeList.clear();
        int type = TypeValue.MONEY_PAY;
        if (position == 1) {//支出
//                List<PayTable> payByTime = PayTableUtil.getInstance(mapplication).getPayByTime(System.currentTimeMillis() - 1000L * 60L * 60L * 24L * 30L, System.currentTimeMillis());
//                Log.d(TAG, "查出的个数:" + payByTime.size());

            type = TypeValue.MONEY_PAY;
        } else if (position == 2) {//收入
//                List<IncomeTable> incomeByTime = IncomeTableUtil.getInstance(mapplication).getIncomeByTime(System.currentTimeMillis() - 1000 * 60 * 60 * 24 * 30, System.currentTimeMillis());
            type = TypeValue.MONEY_INCOME;
        }

        //查询5个月的
        Calendar c = Calendar.getInstance();
        int month = c.get(Calendar.MONTH);

        for (int i = 0; i < 11; i++) {

            c.set(Calendar.MONTH, month - i);//设置月份

            c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));//设置当月最后一天
            c.set(Calendar.HOUR_OF_DAY, 23);
            c.set(Calendar.MINUTE, 59);
            c.set(Calendar.SECOND, 59);
            c.set(Calendar.MILLISECOND, 999);
            long endTime = c.getTime().getTime();

            c.set(Calendar.DAY_OF_MONTH, 1);//设置当月第一天
            c.set(Calendar.HOUR_OF_DAY, 0);
            c.set(Calendar.MINUTE, 0);
            c.set(Calendar.SECOND, 0);
            c.set(Calendar.MILLISECOND, 0);
            long startTime = c.getTime().getTime();

            List<MoneyTable> chargeByTime = MoneyTableUtil.getInstance(mapplication).getChargeByTime(startTime, endTime, type);
            chargeList.add(chargeByTime);
        }


    }


    private synchronized void saveContent(String value, int position) {

        if (TextUtils.isEmpty(value))
            return;

        SharedPreferences.Editor edit = sp.edit();
        switch (position) {
            case 0:
                edit.putString("today", value).apply();
                break;
            case 1:
                edit.putString("week", value).apply();
                break;
            case 2:
                edit.putString("month", value).apply();
                break;
        }
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        View view = (View) object;
        container.removeView(view);
    }


    private void editType(View view, int position) {
        EditText content = view.findViewById(R.id.content);

        if (content != null) {
            content.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {

                    if (s == null)
                        return;
                    String value = s.toString();

                    saveContent(value, position);
                }
            });

        }

    }

} 